import {
  Card,
  ConfigProvider,
  Descriptions,
  Input,
  theme,
  Typography,
} from 'antd';
import lodash from 'lodash';
import React, { useRef, useState } from 'react';
import { ArrayLngLat, InfoWindow, Map, MapProps, Marker } from 'react-amap';
const { Search } = Input;
export type LocationValue = {
  /**
   * 位置名称
   */
  name?: string;
  /**
   * 位置坐标
   */
  location?: number[] | string[];
  /**
   * 省
   */
  country?: string;
  /**
   * 省
   */
  province?: string;
  /**
   * 市
   */
  citycode?: string;
  /**
   * 市
   */
  city?: string;
  /**
   * 区县
   */
  district?: string;
  /**
   * 街道
   */
  towncode?: string;
  /**
   * 街道
   */
  township?: string;
  /**
   * 路号
   */
  streetNumber?: string;
  /**
   * 路
   */
  street?: string;
  /**
   * 详细地址
   */
  address?: string;
};

export type SfwAmapLocationSelectProps = Omit<MapProps, 'onChange'> & {
  width?: number;
  height?: number;
  readOnly?: boolean;
  value?: LocationValue;
  onChange: (value?: LocationValue) => void;
};

const SfwAmapLocationSelect: React.FC<SfwAmapLocationSelectProps> = (
  props: any,
) => {
  const { width, height, readOnly = false, value, onChange, ...rest } = props;
  const { token } = theme.useToken();
  // const { message } = App.useApp();
  // const markerPosition = value?.location as ArrayLngLat;
  const [markerPosition, setMarkerPosition] = useState<ArrayLngLat | null>(
    value?.location,
  );
  const mapCenter = value?.location as ArrayLngLat;
  // const plugins = ['Geocoder', 'PlaceSearch'];
  const events: any = {
    created: () => {
      window.AMap.plugin('AMap.Geocoder', () => {});
      window.AMap.plugin('AMap.PlaceSearch', () => {});
    },
  };

  // 使用 useRef 存储 map 和 placeSearch 实例的引用
  const mapRef = useRef<any>(null);
  // 在 events.created 中初始化 placeSearch 实例
  // 搜索地点处理函数
  const handleSearch = (keyword: string) => {
    const placeSearch = new window.AMap.PlaceSearch({
      pageSize: 5, // 设置每页显示结果的数量，默认为10
      pageIndex: 1, // 设置查询结果的页码，默认为1
      // 其他配置...
    });
    if (!placeSearch) {
      console.log('placeSearch未初始化');
      return;
    } // 确保 placeSearch 已初始化
    placeSearch.search(keyword, (status: any, result: any) => {
      if (status === 'complete' && result.info === 'OK') {
        console.log('搜索成功');
        // 处理搜索结果，例如更新 marker 或 infoWindow
        const poi = result.poiList.pois[0]; //
        console.log('poi', poi);
        if (poi) {
          const { location, name, address } = poi;
          const lnglat = [parseFloat(location.R), parseFloat(location.Q)];
          console.log('lnglat', lnglat);
          // 更新地图中心和标记
          mapRef.current?.setCenter(lnglat);
          setMarkerPosition(lnglat);
          // 更新选择的值并触发 onChange
          const locationValue: LocationValue = {
            name,
            location: lnglat,
            address,
            // 其他属性可以根据需要添加
          };
          onChange?.(locationValue);
        }
      } else {
        console.log('搜索失败:', result);
      }
    });
  };
  if (!readOnly) {
    const getAddress = (options: { location: string[]; name?: string }) => {
      const { name, location } = options;
      const geocoder = new window.AMap.Geocoder({
        city: '010', // 城市，默认：“全国”
      });
      geocoder.getAddress(location, (status: any, result: any) => {
        if (!(status === 'complete' && result.info === 'OK')) {
          onChange?.(undefined);
          return;
        }

        // adcode : "510112"
        // building : ""
        // buildingType : ""
        // businessAreas : []
        // city : "成都市"
        // citycode : "028"
        // district : "龙泉驿区"
        // neighborhood : ""
        // neighborhoodType : ""
        // province : "四川省"
        // street : ""
        // streetNumber : ""
        // towncode : "510112004000"
        // township : "十陵街道"
        const {
          country,
          province,
          citycode,
          city,
          district,
          towncode,
          township,
          streetNumber,
          street,
        } = result.regeocode.addressComponent;
        const address = result.regeocode.formattedAddress;
        const locationValue: LocationValue = {
          name,
          location,
          country,
          province,
          citycode,
          city,
          district,
          towncode,
          township,
          streetNumber,
          street,
          address,
        };
        // console.info('选择地址：', locationValue);
        onChange?.(locationValue);
      });
    };
    // 地图点击事件
    events.dblclick = (e: any) => {
      const { lnglat } = e;
      const { lng, lat } = lnglat;
      const location = [lng, lat];
      getAddress({ location });
    };

    // 地图热点点击事件
    events.hotspotclick = (e: any) => {
      const placeSearch = new window.AMap.PlaceSearch({
        city: '010', // 城市，默认：“全国”
      });
      placeSearch.getDetails(e.id, function (status: any, result: any) {
        if (!(status === 'complete' && result.info === 'OK')) {
          return;
        }
        const pois = result.poiList.pois;
        const poi = lodash.head(pois) as any;
        if (!poi) {
          return;
        }
        const { location: locationStr, name, address } = poi;
        const location = lodash.split(locationStr, ',');
        console.log(address);
        getAddress({ location, name });
      });
    };
  }

  const mapProps = {
    amapkey: `788e08def03f95c670944fe2c78fa76f`,
    // version: `2.0`,
    zoom: 17,
    // plugins: plugins,
    events: events,
    doubleClickZoom: false,
    ...rest,
  };
  if (mapCenter) {
    mapProps.center = mapCenter;
  }

  return (
    <Card
      bordered
      style={{
        overflow: 'hidden',
        width: width || 480,
        height: height || 480,
      }}
      styles={{
        body: {
          padding: 0,
          width: '100%',
          height: '100%',
        },
      }}
    >
      <Search
        enterButton
        placeholder="输入关键词搜索地点"
        onSearch={handleSearch}
        style={{ marginBottom: 16 }}
      />
      <Map {...mapProps}>
        {markerPosition && (
          <InfoWindow
            position={markerPosition}
            visible={!!value}
            autoMove={false}
            isCustom
            offset={[0, -34]}
            // offset={[0, -42]}// 2.0版本
          >
            <ConfigProvider
              theme={{
                token: {
                  fontSize: token.fontSizeSM,
                },
                components: {
                  Descriptions: {
                    titleMarginBottom: 0,
                    itemPaddingBottom: 0,
                  },
                },
              }}
            >
              <Descriptions
                style={{
                  width: 400,
                }}
                column={1}
                title={value?.name || `选中位置`}
                items={[
                  {
                    key: '1',
                    label: '坐标',
                    children: lodash.join(value?.location, ','),
                  },
                  // {
                  //   key: '2',
                  //   label: '位置',
                  //   children: `${value?.province} ${value?.city} ${value?.district
                  //     } ${value?.township} ${value?.street || ''} ${value?.streetNumber || ''
                  //     }`,
                  // },
                  {
                    key: '3',
                    label: '地址',
                    children: (
                      <Typography.Paragraph copyable>
                        {value?.address || '未知地址'}
                      </Typography.Paragraph>
                    ),
                  },
                ]}
              />
            </ConfigProvider>
          </InfoWindow>
        )}
        {markerPosition && <Marker position={markerPosition} />}
      </Map>
    </Card>
  );
};

export default SfwAmapLocationSelect;
